package heliotrope.net.loader
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;
	/**
	 * ImgLoader类是一个用于为显示对象加载图片资源的类
	 * 其获取指定url中的图片资源，将资源放入一个Bitmap对象中
	 * 并调用构造函数中所指定的目标(target)的指定方法或者属性来存储此Bitmap对象
	 * */
	public class ImgLoader extends EventDispatcher implements ILoader
	{
		private var _loader:Loader;
		private var _url:URLRequest;
		private var _target:ILoadTarget;

		public function ImgLoader()
		{
			_loader = new Loader;
		}
		
		public function load(url:String, target_:ILoadTarget):void
		{
			_url = new URLRequest(url);
			try
			{
				addListeners()
				_loader.load(_url);
			}
			catch(error:Error)
			{
				trace("Can't load!" + error.message);
			}
			_target = target_;
		}
		
//		override public function removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void
//		{
//			super.removeEventListener(type, listener, useCapture);
//			remove();
//		}
		
		protected function addListeners():void
		{
			_loader.contentLoaderInfo.addEventListener(Event.COMPLETE,completeHandler);
			_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,ioErrorHandler);
			_loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, progressHandler);
		}
		
		
		protected function delListeners():void
		{
			_loader.contentLoaderInfo.removeEventListener(Event.COMPLETE,completeHandler);
			_loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR,ioErrorHandler);
			_loader.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS, progressHandler);
		}
		
		protected function completeHandler(event:Event):void
		{
			_target.saveData(event.target.content["bitmapData"]);
			dispatchEvent(event);
		}
		
		protected function progressHandler(event:ProgressEvent):void
		{
			dispatchEvent(event);
		}
		
		protected function ioErrorHandler(event:IOErrorEvent):void
		{
			//====the code below is necessary====
			try
			{
				_loader.close();
			}
			catch(error:Error)
			{
				trace("Loader closing error:"+error);
			}
			//====================================
			dispatchEvent(event);
			//trace(evt.type + " at " + this.toString() + _url.url);
			//Alert.show("读取文件出错，未找到文件！");
		}
		
		public function unload():void
		{
			remove();
		}
		
		protected function remove():void
		{
			delListeners();
			_target = null;
			try
			{
				_loader.close();
			}
			catch(error:Error)
			{
				trace("Loader closing error:"+error);
			}
			_loader.unloadAndStop();
		}
		
		public function get target():ILoadTarget
		{
			return _target;
		}
	}
}